<?php
/**
 * Flash业务数据控制
 * @author roger
 *
 */
namespace app\index\service;

use utils\JssdkWechat;

class WechatServer {
	
	protected $token = "fjcdm";
	
	/**
	 * 获取微信消息
	 * @param unknown_type $data
	 * @return multitype:string NULL 
	 */
	private function getWeixinMsg($data) {
		$msg = array();
		$postObj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        $msg['FromUserName'] = $postObj->FromUserName;
        $msg['ToUserName'] = $postObj->ToUserName;
        $msg['Content'] = trim($postObj->Content);
        $msg['CreateTime'] = trim($postObj->CreateTime);
        $msg['MsgType'] = $postObj->MsgType;
        if ( $msg['MsgType'] == "event") {
        	$msg['Event'] = $postObj->Event;
        }
        //$msg['EventKey'] = $postObj->EventKey;
        return $msg;
	}
	
	/**
     * 根据用户消息进行反馈
     * @param unknown_type $data
     * @return string|boolean
     */
    public function responseMsg($data)
    {
    	$wx_msg = $this->getWeixinMsg($data);
    	$msg = $this->dealMsg($wx_msg);
      	$CreateTime = time();
		$type = $msg['type'];
		$flag = ( isset($msg['flag']) and $msg['flag'] )? 1 : 0;
		if( $type == 'text' ){
			$Content = "<Content><![CDATA["."reply".$wx_msg['FromUserName'].$msg['Content']."]]></Content>";
		}else if( $type == 'music' ){
			$Content = "<Music>
						<Title><![CDATA[".$msg['title']."]]></Title>
						<Description><![CDATA[".$msg['description']."]]></Description>
						<MusicUrl><![CDATA[".$msg['musicurl']."]]></MusicUrl>
						<HQMusicUrl><![CDATA[".$msg['hqmusicurl']."]]></HQMusicUrl>
						</Music>";
		}else if( $type == 'news' ){
			$itemsCount = count( $msg['items'] ) < 10 ? count( $msg['items'] ) : 10;//最大10
			$newTplHeader = "<ArticleCount>".$itemsCount."</ArticleCount>
							 <Articles>";				
			$Content = '';
			foreach( $msg['items'] as $key => $val ){
				if( $key <= 9 ){//最大10
		        	$Content .= "<item>
								 <Title><![CDATA[".$val['title']."]]></Title> 
								 <Description><![CDATA[".$val['description']."]]></Description>
								 <PicUrl><![CDATA[".$val['picurl']."]]></PicUrl>
								 <Url><![CDATA[".$val['url']."]]></Url>
								 </item>";
		        	continue;
				}
				break;
		    }
			$newTplFoot = "</Articles>";
			$Content = $newTplHeader . $Content . $newTplFoot;
		}
		$header = "<xml>
				   <ToUserName><![CDATA[".$wx_msg['FromUserName']."]]></ToUserName>
				   <FromUserName><![CDATA[".$wx_msg['ToUserName']."]]></FromUserName>
				   <CreateTime>".$CreateTime."</CreateTime>
				   <MsgType><![CDATA[".$type."]]></MsgType>";
		$footer = "<FuncFlag>".$flag."</FuncFlag>
				   </xml>";
                  
		return $header . $Content . $footer;
    }
    
	//验证
	public function valid( $echostr,$signature,$timestamp,$nonce ){
        if($this->checkSignature( $signature,$timestamp,$nonce )){
        	echo $echostr;
        	exit;
        }
	}
	
	/**
	 * 检查接入微信合法性
	 * @param unknown_type $signature
	 * @param unknown_type $timestamp
	 * @param unknown_type $nonce
	 * @return boolean
	 */
	private function checkSignature($signature,$timestamp,$nonce)
	{	
		$token = $this->token;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	
    /**
     * 消息处理
     * @param unknown_type $wx_msg
     */
    private function dealMsg($wx_msg) {
	    if( $wx_msg['MsgType'] == 'event' and $wx_msg['Event'] == 'unsubscribe' ){
			//用户取消关注事件
			exit;//结束程序
		}else if( $wx_msg['MsgType'] == 'event' and $wx_msg['Event'] == 'subscribe' ){
			//关注成功后的信息
			$note = array(
				'type' => 'text',
				'Content'=> "您好，此公告帐号为视易测试帐号"."\n"."感谢您的支持！"."\n"."，发送歌名就可以听歌哦，快试试！"
			);
		} else {
			$note = array(
				'type' => 'text',
				'Content'=> $wx_msg['Content']
			);
		}
		return $note;
    }

    /**
     * 判断是否为微信header
     * @return bool
     */
    public function isWeixin() {
        $agent = $_SERVER["HTTP_USER_AGENT"];
        $isweixin = preg_match('/MicroMessenger/',$agent);
        if ( $isweixin ) {
            return true;
        }
        return false;
    }

    /**
     * 获取微信认证包数据
     * @return array
     */
    public function getWeixinSignPackage($p_url='') {

        if ( $this->isWeixin() ){

            require_once "./Apps/Common/Lib/jssdk.php";
            $jssdk = new \JSSDK(C('WX_APPID'), C('WX_APPSECRET'));
            $signPackage = $jssdk->GetSignPackage($p_url);

            return $signPackage;
        }
    }

    /**
     * K米欢乐购公众号专用
     * @param $p_url
     * @param $p_appid
     * @param $p_appkey
     * @return array
     */
    public function getWeixinKmihlgSignPackage($p_url,$p_appid,$p_appkey) {

        if ( $this->isWeixin() ){
            $jssdk = new JssdkWechat($p_appid, $p_appkey);
            $signPackage = $jssdk->GetSignPackage($p_url,'xwm');

            return $signPackage;
        }
    }
}
